<template>
  <div class="containers">
    <div id="bpmn-view"></div>
  </div>
  <Table :tableData="tableData" :havePage="false" :columnData="columnData" />
</template>

<script>
import Table from "../../../components/Table.vue";
import { createNamespacedHelpers } from "vuex";
const { mapActions } = createNamespacedHelpers("historyListStore");
import { timestampToTime } from "@/utils/currency.js";

import bpmn from "bpmn-js";
export default {
  name: "Modal",
  data() {
    return {
      tableData: [], //表格数据
      bpmnXML: "",
      taskDefinitionKey: "", //当前任务
      activeId: "",
      columnData: [
        { title: "当前环节", prop: "name" },
        { title: "批注人姓名", prop: "userName" },
        {
          title: "批注内容",
          prop: "createTime",
          formatter: (row) => {
            return `<div>${row.comment
              .map((item) => item.message)
              .join(",")}</div>`;
          },
        },
        {
          title: "任务开始时间",
          prop: "startTime",
          formatter: (row) => {
            return timestampToTime(row.startTime);
          },
        },
        {
          title: "批注时间",
          prop: "endTime",
          formatter: (row) => {
            return timestampToTime(row.endTime);
          },
        },
      ], //表头数据
      pageOption: {},
    };
  },
  props: {
    data: {
      type: Object,
      default: function() {
        return {
          processIntanceId: "", //流程实例id
          processDefinitionId: "", //流程定义id
        };
      },
    },
  },
  methods: {
    ...mapActions([
      "flowTrackByProcessInstanceId",
      "getFlowBpmn",
      "getBpmnXML",
      "getTaskCurrent",
    ]),
    async getTableData(data) {
      var res = await this.flowTrackByProcessInstanceId(data.processIntanceId);
      var rst = await this.getFlowBpmn(data.processDefinitionId);
      this.tableData = res;
      var TaskData1 = await this.getTaskCurrent(data.processIntanceId);
      var TaskData = TaskData1?.[0];
      var taskDefinitionKey = TaskData?.taskDefinitionKey;
      this.initBpmn(taskDefinitionKey, rst);
    },
    initBpmn(taskDefinitionKey, XMLData) {
      var viewer = new bpmn({
        container: "#bpmn-view",
      });

      viewer.importXML(XMLData.content, (err) => {
        if (err) {
          console.error(err);
        } else {
          // 这里是成功之后的回调, 可以在这里做一系列事情
          // var overlays = viewer.get("overlays"); //获取over视图
          var elementRegistry = viewer.get("elementRegistry");
          if (taskDefinitionKey) {
            var shape = elementRegistry.get(taskDefinitionKey);
            var arr = [];
            this.tableData.map((itme) => {
              arr.push(itme.taskDefinitionKey);
            });
            let canvas = viewer.get("canvas");
            canvas.zoom("fit-viewport", "auto");
            // nodeCodes为需要设置高亮颜色的部分的id的集合（xml文件中<flowNodeRef>****</flowNodeRef>标签里的部分），这个数据也是从接口获取，这里从xml中随便取出几个测试用
            this.setNodeColor(arr, "nodeSuccess", canvas);
            this.setNodeColor([shape], "nodeSuccessa", canvas);
          }
          this.addEventBusListener(viewer);
        }
      });
    },
    // 设置高亮颜色的class
    setNodeColor(nodeCodes, colorClass, canvas) {
      for (let i = 0; i < nodeCodes.length; i++) {
        canvas.addMarker(nodeCodes[i], colorClass);
      }
    },
    /**
     * @description: 设立监听
     * @param {*} bpmnModeler
     * @return {*}
     */
    addEventBusListener(bpmnModeler) {
      var that = this;
      const overlays = bpmnModeler.get("overlays");
      const eventBus = bpmnModeler.get("eventBus"); // 需要使用eventBus
      const eventTypes = ["element.hover", "element.click"]; // 需要监听的事件集合
      const bpmn_htmls = document.getElementsByClassName("highlight-boder");
      bpmn_htmls.forEach((item) => {
        item.addEventListener("mouseenter", () => {
          if (this.activeId) {
            overlays.remove(this.activeId);
          }
          let div = document.createElement("div");
          div.innerHTML = `<div id='tiplayer' style='position:absolute;z-index:999;top:-50px'>啊啊啊啊</div>`;
          div.classList.add("bpmn_msg");
          item.appendChild(div);
        });
        item.addEventListener("mouseleave", () => {
          if (this.activeId) {
            overlays.remove(this.activeId);
          }
          let classList = document.getElementsByClassName("bpmn_msg");
          classList.forEach((i) => {
            item.removeChild(i);
          });
        });
      });
      eventTypes.forEach(function(eventType) {
        eventBus.on(eventType, function(e) {
          if (!e) return;
          if (e.element.type == "bpmn:Process") {
            overlays.remove(that.activeId);
            return;
          }
          switch (eventType) {
            case "element.hover":
              that.elementHover(bpmnModeler, overlays, e);
              break;
            case "element.click":
              break;
            default:
              break;
          }
        });
      });
    },
    /**
     * @description: 鼠标划过事件
     * @param {*}
     * @return {*}
     */

    elementHover(bpmnModeler, overlays, e) {
      let info = this.tableData.filter(
        (item) => item.name === e.gfx.textContent
      );
      if (!info.length) return;
      if (this.activeId) {
        overlays.remove(this.activeId);
      }
      if (
        e.element.type == "bpmn:StartEvent" ||
        e.element.type == "bpmn:SequenceFlow" ||
        e.element.type == "label" ||
        e.element.type == "bpmn:EndEvent"
      ) {
        return;
      }
      var elementId = overlays.add(e.element.id, {
        position: {
          top: -50,
        },
        html: `<div id='tiplayer'>${info.map((item) => {
          return ` <p>审批人:${item.userName}</p>
                <p>审批时间:${this.$dayjs.formateDate(
                  item.createTime,
                  "YYYY-MM-DD hh:mm:ss"
                )}</p>`;
        })}</div>`,
      });
      this.activeId = elementId;
    },
  },
  components: {
    Table,
  },
  //生命周期 - 创建完成（访问当前this实例）
  // created() {},
  //生命周期 - 挂载完成（访问DOM元素）

  watch: {
    "data": function() {
     this.getTableData(this.data);
    },
  },
  mounted() {
    this.getTableData(this.data);
  },
};
</script>
<style lang="scss">
.bpmn_msg {
  color: red;
}
</style>
<style scoped lang="scss">
/* @import url(); 引入scss类 */
.canvas {
  margin: 10px;
}
/deep/ .nodeSuccess:not(.djs-connection) {
  .djs-visual {
    > :nth-child(1) {
      stroke: green !important;
      stroke-width: 3px !important;
    }
  }
}
/deep/ .nodeSuccessa:not(.djs-connection) {
  .djs-visual {
    > :nth-child(1) {
      fill: green !important;
      fill-opacity: 0.4 !important;
    }
  }
}
.containers {
  background-color: #ffffff;
  width: 100%;
  height: 50vh;
  overflow: hidden;
  #bpmn-view {
    width: 100%;
    height: 100%;
    /deep/ .viewport {
      margin: 0 auto;
    }
    /deep/ #verify_01 {
      background: red;
    }
    /deep/ #tiplayer {
      background: green;
      padding: 10px;
      position: absolute;
      z-index: 999;
      left: 111px;
      top: 40px;
      width: auto;
      height: auto;
      & > p {
        color: #fff;
        white-space: nowrap;
      }
      &::after {
        content: "";
        position: absolute;
        left: -20px;
        z-index: 9999;
        top: 40px;
        border: 10px solid;
        border-color: transparent green transparent transparent;
      }
    }

    /deep/ .bjs-powered-by {
      display: none;
    }
  }
  .bjs-powered-by {
    display: none;
  }
}
</style>
